package com.xy.fragment1.ui.main;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;

import com.xy.fragment1.R;
import com.xy.fragment1.util.UILog;

import java.util.Calendar;
import java.util.List;

import static android.app.Activity.RESULT_OK;

public class MainFragment extends Fragment {

    private MainViewModel mViewModel;

    private static final int PICK_CONTACT_REQUEST = 1;
    private static final int PICK_CONTACT_REQUEST2 = 2;

    public static MainFragment newInstance() {
        return new MainFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.main_fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        // TODO: Use the ViewModel
        final UILog log = new UILog(this.getActivity());
        Button callat137Btn = this.getActivity().findViewById(R.id.callat137);
        callat137Btn.setOnClickListener(v -> {
            try {
                log.info("call phone clicked");
                Intent callPhtoneIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:13758494529"));
                log.info("now call at 13758494529");
                PackageManager pm = this.getActivity().getPackageManager();
                List<ResolveInfo> activities = pm.queryIntentActivities(callPhtoneIntent, 0);
                String out = "activities: ";
                for (ResolveInfo ri : activities) {
                    out += ri + ";";
                }
                log.info(out);

                startActivity(callPhtoneIntent);


            } catch (Exception e) {
                log.info(e.getMessage());
            }
        });
        Button locBtn = this.getActivity().findViewById(R.id.location);
        locBtn.setOnClickListener(v -> {
            log.info("location clocked");
            // Build the intent
            Uri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California");
            Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);

            // Verify it resolves
            PackageManager packageManager = this.getActivity().getPackageManager();
            List<ResolveInfo> activities = packageManager.queryIntentActivities(mapIntent, 0);
            boolean isIntentSafe = activities.size() > 0;

            // Start an activity if it's safe
            if (isIntentSafe) {
                startActivity(mapIntent);
            }
            log.info("location activity OK!");
        });

        Button emailBtn = this.getActivity().findViewById(R.id.email);
        emailBtn.setOnClickListener(v -> {
            log.info("Send e-mail clicked");
            Intent emailIntent = new Intent(Intent.ACTION_SEND);
            // The intent does not have a URI, so declare the "text/plain" MIME type
            emailIntent.setType("text/plain");
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"xiuye_engineer@outlook.com"}); // recipients
            emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Email subject");
            emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message text");
            emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://path/to/email/attachment"));
            // You can also attach multiple items by passing an ArrayList of Uris
            this.startActivity(emailIntent);
            log.info("Send email OK!");
        });

        Button webBtn = this.getActivity().findViewById(R.id.web);
        webBtn.setOnClickListener(v -> {
            log.info("web clicked");
            Uri webpage = Uri.parse("https://www.baidu.com");
            Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
            this.startActivity(webIntent);
            log.info("open web page baidu OK!");
        });
        Button calendarBtn = this.getActivity().findViewById(R.id.calendar);
        calendarBtn.setOnClickListener(v -> {
            log.info("calendar clicked");
            Intent calendarIntent = new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);
            Calendar beginTime = Calendar.getInstance();
            beginTime.set(2012, 0, 19, 7, 30);
            Calendar endTime = Calendar.getInstance();
            endTime.set(2012, 0, 19, 10, 30);
            calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis());
            calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis());
            calendarIntent.putExtra(CalendarContract.Events.TITLE, "Ninja class");
            calendarIntent.putExtra(CalendarContract.Events.EVENT_LOCATION, "Secret dojo");
            this.startActivity(calendarIntent);
            log.info("calendar settings OK!");
        });
        Button chooser = getActivity().findViewById(R.id.chooser);
        chooser.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_SEND);


            // Always use string resources for UI text.
            // This says something like "Share this photo with"
            String title = "Intent chooser";
            // Create intent to show chooser
            Intent chooserIntent = Intent.createChooser(intent, title);

            // Verify the intent will resolve to at least one activity
            if (intent.resolveActivity(this.getActivity().getPackageManager()) != null) {
                startActivity(chooserIntent);
                log.info("chooser OK!");
            }


        });
        this.getActivity().findViewById(R.id.sharePicture).setOnClickListener(v->{
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.putExtra(Intent.EXTRA_TEXT,"Hello");
            intent.putExtra(Intent.EXTRA_TITLE,"Send Message");
//            intent.setClipData();
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            startActivity(Intent.createChooser(intent,null));

        });


        this.getActivity().findViewById(R.id.result).setOnClickListener(v -> {
            Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
            pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
            startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
        });
        this.getActivity().findViewById(R.id.selfAction).setOnClickListener(v->{
            log.info("self action clicked");
            Intent intent = new Intent("com.xy.DEMO_ACTION");
            this.startActivity(intent);
            log.info("open intent action for activity OK!");
        });
        this.getActivity().findViewById(R.id.main2Activity).setOnClickListener(v->{
            log.info("redirect to Main2Activity");
            Intent intent = new Intent("com.xy.DEMO_ACTION",Uri.parse("https://www.xiuye.com/java/123"));

            List<ResolveInfo> activities = this.getActivity().getPackageManager().queryIntentActivities(intent,PackageManager.GET_ACTIVITIES);
            boolean isIntentSafe = activities.size() > 0;
            // Start an activity if it's safe
            if (isIntentSafe) {
//                startActivity(intent);
                this.startActivityForResult(intent,PICK_CONTACT_REQUEST2);
            }
            log.info("Main2Activity OK!"+activities);
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        final UILog log = new UILog(this.getActivity());
        // Check which request it is that we're responding to
        if (requestCode == PICK_CONTACT_REQUEST) {
            // Make sure the request was successful
            if (resultCode == RESULT_OK) {
                // Get the URI that points to the selected contact
                Uri contactUri = data.getData();
                // We only need the NUMBER column, because there will be only one row in the result
                String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};

                // Perform the query on the contact to get the NUMBER column
                // We don't need a selection or sort order (there's only one result for the given URI)
                // CAUTION: The query() method should be called from a separate thread to avoid blocking
                // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
                // Consider using <code><a href="/reference/android/content/CursorLoader.html">CursorLoader</a></code> to perform the query.
                Cursor cursor = this.getActivity().getContentResolver()
                        .query(contactUri, projection, null, null, null);
                cursor.moveToFirst();

                // Retrieve the phone number from the NUMBER column
                int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                String number = cursor.getString(column);

                // Do something with the phone number...
                log.info(contactUri+"\n;phone: " + number);
            }
        }
        else if(requestCode==PICK_CONTACT_REQUEST2){
            if(resultCode==RESULT_OK){
                log.info(data+"");
            }

        }
    }
}
